<template>
  <div>
    <el-progress v-bind="$attrs" v-on="$listeners" :percentage="processInt"></el-progress>
  </div>
</template>

<script>
export default {
  name: 'Progress',

  components: {},

  inheritAttrs: false,

  props: {
    visible: {
      type: Boolean,
      default: false
    },
    state: {
      type: String,
      default: 'P'
    }
  },

  data() {
    this.step = 0.3;
    this.progressTimer = null;
    return { process: 0 };
  },

  computed: {
    processInt() {
      return parseInt(this.process);
    }
  },

  watch: {
    state(val) {
      if (val === 'S') {
        this.step = 3;
      }
    }
  },

  beforeMount() {},

  mounted() {
    this.startProgress();
  },

  beforeDestroy() {
    this.clearTimer('progressTimer');
  },

  methods: {
    startProgress() {
      this.clearTimer('progressTimer');
      this.progressTimer = setInterval(() => {
        this.updateProcess();
      }, 50);
    },
    updateProcess() {
      this.process = Math.min(this.process + this.step, 100);
      if (this.state === 'F') {
        this.clearTimer('progressTimer');
        this.$emit('done', 'break');
        this.$emit('update:visible', false);
        return;
      }

      if (this.process >= 99 && this.state === 'P') {
        this.clearTimer('progressTimer');
        setTimeout(() => {
          this.$emit('done', 'timeout');
          this.$emit('update:visible', false);
        }, 3000);
        return;
      }

      if (this.process >= 60 && this.state === 'P') {
        this.step = 0.005;
      }

      if (this.process >= 100) {
        this.clearTimer('progressTimer');
        this.$emit('done', 'complete');
        this.$emit('update:visible', false);
      }
    },
    clearTimer(name) {
      if (this[name]) {
        clearInterval(this[name]);
        clearTimeout(this[name]);
        this[name] = null;
      }
    }
  }
};
</script>
<style lang="scss" scoped></style>
